package com.azxcrm.framework.redis.template.service;

import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.azxcrm.common.exception.base.BaseException;
import com.azxcrm.framework.redis.template.RedisService;

/**
 * RedisTemplate的二次封装实现方法
 * @author Dustyone
 *
 */
@Service
public class RedisServiceImpl implements RedisService {

	private static final Logger log = LoggerFactory.getLogger(RedisServiceImpl.class);
	
	//引入 Spring封装好了的RedisTemplate
	@Resource
	private RedisTemplate<String, Object> redisTemplate;

	@Override
	public boolean set(String key, String value) throws BaseException {
		boolean flag = false;
		try {
			this.redisTemplate.opsForValue().set(key, value);
			flag = this.redisTemplate.opsForValue().get(key) == null
					|| "".equals(this.redisTemplate.opsForValue().get(key)) ? false : true;
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			throw new BaseException("RedisConnection","get redis thread from the pool failed");
		}
		return flag;
	}

	@Override
	public Object get(String key) throws BaseException {
		Object retsult = null;
		try {
			retsult = this.redisTemplate.opsForValue().get(key);
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			throw new BaseException("get redis thread from the pool failed");
		}
		return retsult;
	}

	@Override
	public boolean expire(String key, long expire) throws BaseException {
		boolean flag = false;
		try {
			flag = redisTemplate.expire(key, expire, TimeUnit.SECONDS);
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			throw new BaseException("get redis thread from the pool failed");
		}
		return flag;
	}

	@Override
	public <T> boolean setList(String key, List<T> list) throws BaseException {
		return false;
	}

	@Override
	public <T> List<T> getList(String key, Class<T> clz) throws BaseException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long setObject(String key, Object obj) throws BaseException {
		long ret = -1;
		try {
			this.redisTemplate.opsForValue().set(key, obj);
			ret = this.redisTemplate.opsForValue().get(key) == null
					|| "".equals(this.redisTemplate.opsForValue().get(key)) ? -1 : 1;
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			throw new BaseException("get redis thread from the pool failed");
		}
		return ret;
	}

	@Override
	public long getObject(String key, Object obj) {
		// TODO Auto-generated method stub
		return 0;
	}

}
